package SparkShiXun

import java.io.FileInputStream
import java.util.{Properties, Random}

/**
  * Created by Administrator on 2016/9/9 0009.
  */
object IPUtil {

  def getRandomIp: String = {
    val range: Array[Array[Int]] = Array(
      Array(607649792, 608174079),
      Array(1038614528, 1039007743),
      Array(1783627776, 1784676351),
      Array(2035023872, 2035154943),
      Array(2078801920, 2079064063),
      Array(-1950089216, -1948778497),
      Array(-1425539072, -1425014785),
      Array(-1236271104, -1235419137),
      Array(-770113536, -768606209),
      Array(-569376768, -564133889)
    )
    val rdint: Random = new Random
    val index: Int = rdint.nextInt(10)
    val ip: String = num2ip(range(index)(0) + new Random().nextInt(range(index)(1) - range(index)(0)))
    return ip
  }


  def num2ip(ip: Int): String = {
    val b: Array[Int] = new Array[Int](4)
    var x: String = ""
    b(0) = ((ip >> 24) & 0xff).toInt
    b(1) = ((ip >> 16) & 0xff).toInt
    b(2) = ((ip >> 8) & 0xff).toInt
    b(3) = (ip & 0xff).toInt
    x = Integer.toString(b(0)) + "." + Integer.toString(b(1)) + "." + Integer.toString(b(2)) + "." + Integer.toString(b(3))
    return x
  }


  //将ip转换成十进制
  def ipToLong(ip: String): Long = {
    val fragments = ip.split("[.]")
    var ipNum = 0L
    for (i <- 0 until fragments.length) {
      ipNum = fragments(i).toLong | ipNum << 8L
    }
    ipNum
  }

  //二分查找ip地址对应的地区
  def binarySearch(lines: Array[(String, String, String)], ip: Long): Int = {
    var low = 0
    var high = lines.length - 1
    while (low <= high) {
      val middle = (low + high) / 2
      if ((ip >= lines(middle)._1.toLong) && (ip <= lines(middle)._2.toLong))
        return middle
      if (ip < lines(middle)._1.toLong)
        high = middle - 1
      else {
        low = middle + 1
      }
    }
    -1
  }

  def parseNetIP(localIP: String): String = {
    val properties = new Properties()
    //properties文件要放到resource文件夹下
    val path = Thread.currentThread().getContextClassLoader.getResource("ip_mapping.properties").getPath
    properties.load(new FileInputStream(path))
    properties.getProperty(localIP, "223.72.75.31")
  }
}
